package com.boostor.wechatmsg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.boostor.wechatmsg.common.ResultMsg;
import com.boostor.wechatmsg.config.RestTemplateConfig;
import com.boostor.wechatmsg.pojo.vo.AppMsgListVO;
import com.boostor.wechatmsg.pojo.vo.WeChatRequestDataVO;
import com.boostor.wechatmsg.pojo.vo.WeChatResponseMsgVO;
import com.boostor.wechatmsg.service.WeChatMsgService;
import com.boostor.wechatmsg.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author：wk
 * @Create：2022/4/15/9:31
 * @Description：TODO
 * @Version：1.0
 */
@Service
@Slf4j
public class WeChatMsgServiceImpl implements WeChatMsgService {

//    请求地址
    private static String URL = "https://mp.weixin.qq.com/cgi-bin/appmsg?action=?1&begin=?2&count=?3&fakeid=?4&type=?5&query=?6&token=?7&lang=?8&f=?9&ajax=?0";

//    请求cookie
    private final static String COOKIE_VALUE = "appmsglist_action_3884705726=card; RK=teHkSknA3K; ptcz=6253803906e42f72e50e46ebd02db6b6cb3dd31a6a882c7825249160ff44ad54; ua_id=iUaOgiyUWqr7eerRAAAAAH9BHNfql703J_QDK0oxSI0=; wxuin=50694257923580; mm_lang=zh_CN; pgv_pvid=7263997920; tvfe_boss_uuid=f2478c7aa5b4a9e3; uuid=9e49db5f1a7fe6741b8f7ea3d98ae05c; rand_info=CAESIBrhcDR1/kq9lEM6KYkty4gVZkKXldJs2Rq0vipWlsP4; slave_bizuin=3884705726; data_bizuin=3884705726; bizuin=3884705726; data_ticket=Pb91ObgpYZ97DBARsECx/MDweoSijD3KjeYO4ZFpnr4kd0HQOHTBCea4HAzxQEw7; slave_sid=ZzhoQnNGT0R0RlI5VzJza3pWTE5TdUk0czhmcFhiNnFOTWVBa3NYWXFaRHkweXB1R0ZhNjR5anhVVUJZcFhTNDc3c3RKZ2dyQ0JYbXdOaXFIM0Fyb1A0ajRDTWxrSE9BNmpLa0J1WXRCVjd3M3lKRk9FNFRnaWRucmJEa1d6QjRPY2k2czl2UnJmUEV0ck1G; slave_user=gh_76f3fcdfa1ad; xid=ca142980553261aa881c7917cbb2781e";

//    存储key
    private final static String REDIS_KEY = "oldTitle";

//     存储时间（小时）目前存储一天
    private final static long HOLD_TIME = 60*24;

//    @Resource(name = "restTemplate")
//    private RestTemplate restTemplate;
    private RestTemplate restTemplate = new RestTemplateConfig().restTemplate(new RestTemplateBuilder());

//    @Resource(name = "redisUtils")
//    private RedisUtils redisUtils;
    private RedisUtils redisUtils = new RedisUtils();

    @Override
    public ResultMsg checkIsSelected(RedisTemplate<String,Object> redisTemplate) {
//        封装请求参数
        WeChatRequestDataVO weChatRequestDataVO = new WeChatRequestDataVO(
                "list_ex",0,5,"MzA5ODIwNTAyOQ==",9,
                "","723573528","zh_CN","json",1
        );
//        提取参数
        String action = weChatRequestDataVO.getAction();
        Integer begin = weChatRequestDataVO.getBegin();
        Integer count = weChatRequestDataVO.getCount();
        String fakeid = weChatRequestDataVO.getFakeid();
        Integer type = weChatRequestDataVO.getType();
        String query = weChatRequestDataVO.getQuery();
        String token = weChatRequestDataVO.getToken();
        String lang = weChatRequestDataVO.getLang();
        String f = weChatRequestDataVO.getF();
        Integer ajax = weChatRequestDataVO.getAjax();
//        URL赋值
        String newUrl = WeChatMsgServiceImpl.URL.replace("?1", action)
                .replace("?2", begin.toString())
                .replace("?3", count.toString())
                .replace("?4", fakeid)
                .replace("?5", type.toString())
                .replace("?6", query)
                .replace("?7", token)
                .replace("?8", lang)
                .replace("?9", f)
                .replace("?0", ajax.toString());
//        请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cookie",COOKIE_VALUE);
        HttpEntity<MultiValueMap<String, Object>> requestHeaders = new HttpEntity(null, headers);
//        发送请求
        ResponseEntity<String> forEntity = restTemplate.exchange(newUrl, HttpMethod.GET, requestHeaders, String.class);
//        响应状态
        HttpStatus statusCode = forEntity.getStatusCode();
//        响应内容
        String body = forEntity.getBody();
        log.info("响应状态：{}",statusCode);
        WeChatResponseMsgVO weChatResponseMsgVO = JSONObject.parseObject(body, WeChatResponseMsgVO.class);
        log.info("响应内容格式化：{}",weChatResponseMsgVO);
        List<AppMsgListVO> app_msg_list = weChatResponseMsgVO.getApp_msg_list();
//        新文章标题
        String newTitle = app_msg_list.get(0).getTitle();
//        获取已存储文章标题进行对比
        String oldTitle = null;
        try {
            oldTitle = redisTemplate.opsForValue().get(REDIS_KEY).toString();
        } catch (NullPointerException e) {
            log.error("key不存在！");
            oldTitle = null;
        } finally {
            //        为空，暂未存储旧文章
            Map<String,String> map = new HashMap<>();
            // 如果不存在，默认判定当前文章就是最新文章
            if (StringUtils.isEmpty(oldTitle)) {
                //        将文章标题存储到Redis当中（时效1天）
                redisTemplate.opsForValue().set(REDIS_KEY, newTitle, HOLD_TIME, TimeUnit.MINUTES);
//            redisUtils.set(REDIS_KEY, newTitle, 60, TimeUnit.MINUTES);
//                获取上一篇文章表示旧文章
                //        新文章标题
                String oldTitle2 = app_msg_list.get(1).getTitle();
                map.put("oldTitle",oldTitle2);
                map.put("newTitle",newTitle);
                ResultMsg resultMsg = new ResultMsg(1001, "有最新文章了！",map);
                return resultMsg;
            }
//        如果旧新匹配一致，则暂无新文章
            if (newTitle.equals(oldTitle)) {
                map.put("oldTitle",oldTitle);
                map.put("newTitle",null);
                ResultMsg resultMsg = new ResultMsg(1002, "暂无新文章！！",map);
                return resultMsg;
            }
            map.put("oldTitle",oldTitle);
            map.put("newTitle",newTitle);
            ResultMsg resultMsg = new ResultMsg(1001, "有最新文章了！",map);
//        将新文章标题更新到Redis当中（时效1天）
            redisTemplate.opsForValue().set(REDIS_KEY, newTitle, HOLD_TIME, TimeUnit.MINUTES);
            return resultMsg;
        }
    }


}
